package com.xbj.voa.controller;

import cn.hutool.json.JSONUtil;
import com.xbj.voa.common.shiroAndJwt.JwtUtil;
import com.xbj.voa.common.utils.R;
import com.xbj.voa.controller.form.LoginForm;
import com.xbj.voa.controller.form.RegisterForm;
import com.xbj.voa.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author: 木火
 * @create: 2024-01-14
 * @description:用户模块web接口
 **/
@RestController
@RequestMapping("/user")
@Api("用户模块web接口")
public class UserController {
    private static Logger LOG= LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate redisTemplate;

    @Value("${voa.jwt.cache-expire}")
    private int cacheExpire;

    /**
     * @Author 木火
     * @Date  2024/1/15
     * @Param
     * @Description 用户注册
     **/
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R register(@Valid @RequestBody RegisterForm registerForm){
        LOG.info("用户注册模块,请求报文:"+ JSONUtil.toJsonStr(registerForm));
        //调service执行用户注册业务逻辑
        int userId = userService.registerUser(registerForm.getRegisterCode(), registerForm.getCode(), registerForm.getNickName(), registerForm.getPhoto());
        //获取用户的权限列表
        Set<String> permissions = userService.searchUserPermissions(userId);
        //生成token
        String token = jwtUtil.createToken(userId);
        //将token缓存到redis
        saveCacheToken(token,userId);

        R r = R.ok("用户注册成功").put("token", token).put("permission", permissions);
        LOG.info("用户注册模块,返回报文:"+JSONUtil.toJsonStr(r));
        return r;
    }


    @PostMapping("/login")
    @ApiOperation("用户登陆")
    public R login(@Valid @RequestBody LoginForm loginForm){
        //调service,查看用户是否存在
        Integer userId = userService.login(loginForm.getCode());
        //存在,获取用户权限列表,生成token
        Set<String> permissions = userService.searchUserPermissions(userId);
        String token = jwtUtil.createToken(userId);
        //将token保存到redis
        saveCacheToken(token,userId);
        return R.ok("登陆成功").put("token",token).put("permission",permissions);
    }
    private void saveCacheToken(String token,int userId){
        redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
    }
}
